package util;



import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;

import bean.ContentDataBean;
import myapp.MyApp;

import org.json.JSONException;
import org.json.JSONObject;


import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Dialog;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.DialogInterface.OnClickListener;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.view.ContextThemeWrapper;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ProgressBar;

import androidx.core.content.FileProvider;

import com.bigchun.woodhunter.R;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

public class updateManager {

	private Context mContext;

	//提示语
	private String updateMsg = "";

	//返回的安装包url
	private String apkUrl = "";

	private Dialog noticeDialog;

	private Dialog downloadDialog;
	 /* 下载包安装路径 */
    private static  String savePath = "/sdcard/updatedemo/";

    private static  String saveFileName = savePath + "UpdateDemoRelease.apk";

    /* 进度条与通知ui刷新的handler和msg常量 */
    private ProgressBar mProgress;


    private static final int DOWN_UPDATE = 1;

    private static final int DOWN_OVER = 2;
    private static final int DOWN_ERROR = 4;

    private int progress;

    private Thread downLoadThread;

    private boolean interceptFlag = false;
    private int localVersion = 0;
    private String testdata = "";

    @SuppressLint("HandlerLeak")
	private Handler mHandler = new Handler(){
    	public void handleMessage(Message msg) {
    		switch (msg.what) {
			case DOWN_UPDATE:
				mProgress.setProgress(progress);
				break;
			case DOWN_OVER:
				MyLog.i("ssssssssssssss","sssssdddddddd");
				installApk();
				break;
			case 3:
				showNoticeDialog();
				break;
                case DOWN_ERROR:
                    showNoticeErrorDialog();
                    break;
			default:
				break;
			}
    	};
    };
	private String versionname = "";
	private String updatecontent = "";
	private String enforce = "0";//1是强制更新   0不是强制更新
	private final ContentDataBean.DataBean textContent;

	public updateManager(Context context,int localVersion,String testdata) {//版本号
		this.mContext = context;
		this.localVersion = localVersion;
		this.testdata = testdata;
		textContent = new Gson().fromJson(testdata, new TypeToken<ContentDataBean.DataBean>() {}.getType());
		updateMsg = mContext.getString(R.string.app_can_upload);
	}

	//外部接口让主Activity调用
	public void checkUpdateInfo(){
		/*获取版本号和更新地址   */
		downupdate(); //自己增加的判断函数
//	  	showNoticeDialog();
	}

    public void downupdate() {


				String url; //m.getUserBean().getbigcity();    getPwd
				MyApp m = (MyApp) mContext.getApplicationContext();
		MyLog.e("更新", m.getWebConfig());
				url = m.getWebConfig() + "/api/index/version";
		MyLog.e("version--url", url);
//			    String str = HttpConn.getStr(url,m);
				HashMap<String, String> paramsMap = new HashMap<>();
//				paramsMap.put("version_sign","安卓熙然中文版");
				paramsMap.put("version_sign","安卓熙然英文版");
				RequestManager.getInstance(mContext).requestAsyn(url, RequestManager.TYPE_POST_FORM, paramsMap, new RequestManager.ReqCallBack() {
					@Override
					public void onReqSuccess(Object result) {
						MyLog.e("code--result", result.toString());
						try {
							JSONObject json = new JSONObject(result.toString());

							if (json.getString("code").equals("0")) {
								return;
							}
							if (json.isNull("msg")) {

								return;
							}
							JSONObject jarray = json.getJSONObject("data");
//							"newversion": "1.2.1",
//									"content": "更新内容",
//									"downloadurl": "https://www.fastadmin.net/download.html",
//									"version_sign": "安卓木头英文版",
//									"version_code": 1,
//									"enforce": 1

							versionname = jarray.getString("newversion");
							updatecontent = jarray.getString("content");
							apkUrl = jarray.getString("downloadurl");
							enforce = jarray.getString("enforce");

							int sitevison = Integer.valueOf(jarray.getString("version_code"));
							MyLog.i("", "sitevison是:" + sitevison);
							MyLog.i("获取到了localVersion", "localVersion是:" + localVersion);
							if (sitevison > localVersion) {  //1532595965 1521025559
								Message msg = new Message();
								msg.what = 3;
//								apkUrl = jarray.getString("appdownload");
								mHandler.sendMessage(msg);
								return;
							} else {
								return;
							}
						} catch (JSONException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
							return;
						}
					}

					@Override
					public void onReqFailed(String errorMsg) {
						MyLog.e("result", errorMsg);

					}


				});

	}


    public void newdownload(String url){
    	apkUrl = url;
    	showNoticeDialog();
    }

	private void showNoticeDialog(){
		Builder builder = new Builder(mContext);
		builder.setTitle(textContent.getNew_version_found()+"："+versionname);
		builder.setMessage(updatecontent);
		builder.setPositiveButton(textContent.getNow_upgrading(), new OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				showDownloadDialog();
				dialog.dismiss();
				downloadDialog.setCanceledOnTouchOutside(false);//点击空白的地方不消失
			}
		});
		if ("1".equals(enforce)) {
			//强制更新
//			noticeDialog.setCancelable(false);//可选,点击返回键无效
		}else{
			builder.setNegativeButton(textContent.getLater_on(), new OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					dialog.dismiss();
				}
			});
		}
		noticeDialog = builder.create();
		noticeDialog.setCanceledOnTouchOutside(false);//可选，点击dialog其它地方dismiss无效
		if ("1".equals(enforce)) {
			//强制更新
			noticeDialog.setCancelable(false);//可选,点击返回键无效
		}else{

		}

		noticeDialog.show();


	}

	private void showDownloadDialog(){
		Builder builder = new Builder(new ContextThemeWrapper(mContext, R.style.AlertDialogCustom));
		builder.setTitle(mContext.getString(R.string.soft_upload));
		final LayoutInflater inflater = LayoutInflater.from(mContext);
		View v = inflater.inflate(R.layout.progress, null);
		mProgress = (ProgressBar)v.findViewById(R.id.progress);
		if ("1".equals(enforce)) {
			//强制更新
//			downloadDialog.setCancelable(false);//可选,点击返回键无效
		}else{
			builder.setNegativeButton(mContext.getString(R.string.cancel), new OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					dialog.dismiss();
					interceptFlag = true;
				}
			});
		}
		builder.setView(v);


		downloadDialog = builder.create();
		downloadDialog.setCanceledOnTouchOutside(false);
		if ("1".equals(enforce)) {
			//强制更新
			downloadDialog.setCancelable(false);//可选,点击返回键无效
		}else{
		}
		downloadDialog.show();

		downloadApk();
	}

	private Runnable mdownApkRunnable = new Runnable() {
		@Override
		public void run() {
			try {

				URL url = new URL(apkUrl);
				HttpURLConnection conn = (HttpURLConnection)url.openConnection();
                conn.setRequestProperty("Accept-Encoding", "identity");
				conn.connect();
				if (conn.getResponseCode()==200){
                    int length = conn.getContentLength();
                    InputStream is = conn.getInputStream();

//				savePath = Environment.getExternalStorageDirectory().getPath()+"/update";
//				String[] command = {"chmod", "777", savePath};
//				ProcessBuilder builder = new ProcessBuilder(command);
//				try {
//					builder.start();
//				} catch (IOException e) {
//					e.printStackTrace();
//				}
//				File file = new File(savePath);
//				if (!file.exists()) {
//					file.mkdir();
//				}
//				saveFileName = savePath + "UpdateDemoRelease.apk";
//				File ApkFile = new File(saveFileName);
//				FileOutputStream fos = new FileOutputStream(ApkFile);
                    savePath = Environment.getExternalStorageDirectory().getPath() + "/update";
                    String[] command = {"chmod", "777", savePath};
                    ProcessBuilder builder = new ProcessBuilder(command);
                    try {
                        builder.start();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    File file = new File(savePath);
                    if (!file.exists()) {
                        file.mkdir();
                    }
                    saveFileName = savePath + "UpdateDemoRelease.apk";
                    String apkFile = saveFileName;
                    File ApkFile = new File(apkFile);
                    FileOutputStream fos = new FileOutputStream(ApkFile);
					MyLog.i("aaaaaaaaaaa","sssssssssssss");
                    int count = 0;
                    byte buf[] = new byte[1024];

                    do{
                        int numread = is.read(buf);
						if(numread <= 0){
							//下载完成通知安装
							MyLog.e("下载完成","开始安装");
							mHandler.sendEmptyMessage(DOWN_OVER);
							break;
						}
                        count += numread;
                        progress =(int)(((float)count / length) * 100);
                        //更新进度
						MyLog.e("下载中","numread="+numread+"   count="+count+"    progress="+progress);
                        mHandler.sendEmptyMessage(DOWN_UPDATE);

                        fos.write(buf,0,numread);
                    }while(!interceptFlag);//点击取消就停止下载.
                    fos.close();
                    is.close();
                }else{
                    mHandler.sendEmptyMessage(DOWN_UPDATE);
                }

			} catch (MalformedURLException e) {
				e.printStackTrace();
			} catch(IOException e){
				e.printStackTrace();
			}

		}
	};

	 /**
     * 下载apk
     * @param url
     */

	private void downloadApk(){
		downLoadThread = new Thread(mdownApkRunnable);
		downLoadThread.start();
	}
	 /**
     * 安装apk
     * @param url
     */
	private void installApk(){
		File apkfile = new File(saveFileName);
		if (!apkfile.exists()) {
			return;
		}
		SharedPreferences userInfo = mContext.getSharedPreferences("Appset", Activity.MODE_PRIVATE);
		userInfo.edit().putString("appdataver", "0").commit();
		Intent i = new Intent(Intent.ACTION_VIEW);
		Uri data = Uri.fromFile(apkfile);
		if (Build.VERSION.SDK_INT >= 24) {
			data = FileProvider.getUriForFile(mContext, "com.bigchun.woodhunter.fileprovider", apkfile);
			i.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
		} else {
			data = Uri.fromFile(apkfile);
		}
		i.setDataAndType(data, "application/vnd.android.package-archive");
		mContext.startActivity(i);


	}

    private void showNoticeErrorDialog(){
        Builder builder = new Builder(mContext);
        builder.setTitle(mContext.getString(R.string.soft_upload));
        builder.setMessage(mContext.getString(R.string.data_lost_retry));

        builder.setNegativeButton(mContext.getString(R.string.next_time_say), new OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        noticeDialog = builder.create();
        noticeDialog.setCanceledOnTouchOutside(false);
        noticeDialog.show();
    }
}
